require( '$d/css/common.less' );
require( '../style.less' );
define( [
  'require',
  'jquery',
  'bootstrap',
  'header',
  'bigwe_utils',
  'message',
  'constants',
  'pagination',
  'api',
  'behavior',
  'login',
  'searchMaterial'
], function( require, $, bs, header, bu, ShowTitleMessage, constants ) {
  var behavior = require( 'behavior' ),
    login = require( 'login' ),
    searchMaterial = require( 'searchMaterial' );

  var showTime = require( 'message' ).showTime,
    public_vars = public_vars || {};
  public_vars.$container = $( ".wrap" );
  public_vars.$main = public_vars.$container.find( '.main' );
  public_vars.$list = public_vars.$main.find( '.topic_l_list' );
  public_vars.$selection = public_vars.$main.find( '.selection' );

  public_vars.$search = public_vars.$container.find( '.search_area' );
  public_vars.$srhinpt = public_vars.$search.find( '.search_ipt' );
  public_vars.$srhbtn = public_vars.$search.find( '.search_link' );

  public_vars.$page = true;
  var params = {
    u: require( 'api' ).TOPIC.GET_TOPIC,
    data: {
      p: 1,
      l: 15,
      st: ( new Date() - 24 * 60 * 60 * 1000 ),
      et: ( new Date().getTime() ),
      order: 'score',
      s: 'top.baidu.com,d.weibo.com,top.sogou.com,top.so.com',
      keyword: bu.getUrlParam( location.href, 'keyword' )
    },
    callBack: judge
  };

  function myAjax( opt ) {
    ShowTitleMessage.show( '正在加载...' );
    $.ajax( {
      type: 'post',
      url: opt[ 'u' ],
      data: opt[ 'data' ],
      success: function( data ) {
        if ( $.isFunction( opt[ 'callBack' ] ) ) {
          opt[ 'callBack' ]( data );
        }
      },
      complete: function() {
        ShowTitleMessage.hide();
      },
      error: function( XMLHttpRequest, textStatus, errorThrown ) {
        console.log( textStatus );
        console.log( XMLHttpRequest.status );
        console.log( XMLHttpRequest.readyState );
      }
    } );
  };
  searchMaterial.setInputVal( bu.getUrlParam( location.href, 'keyword' ), true );
  //public_vars.$srhinpt.val(  );
  myAjax( params );



  function judge( data ) {
    var data = typeof data === 'string' ? $.parseJSON( data ) : data;

    sach_list( data );
    if ( public_vars.$page ) {
      var s = ( data.data.total_pages || 0 );
      paging( s );
    }
  };

  /**
   * ========== * 筛选* ==========
   */
  public_vars.$selection.find( '.category.icon_cate' ).on( 'mouseenter', 'span', function( e ) {
    $( '.selection_more' ).fadeIn();
    e.stopPropagation();
  } );
  public_vars.$selection.find( '.selection_more' ).mouseleave( function() {
    $( this ).fadeOut();
  } );

  public_vars.$selection.on( 'click', 'span', selection );

  function selection() {
    if ( $( this ).hasClass( 'green' ) ) {
      return false;
    }
    var t = $( this );
    var t_p = t.parent();
    if ( t_p.hasClass( 'choice' ) && t_p.parent().hasClass( 'icon_cate' ) ) {
      return false;
    }

    var lx = t_p.data( 'sx' );
    var v = t.attr( 'value' );
    if ( t_p.hasClass( 'selection_more' ) ) {
      if ( t.data( 'sw' ) ) {
        return false;
      } else {
        t.attr( 'data-sw', true ).data( 'sw', true ).addClass( 'green' );
        t.siblings().attr( 'data-sw', false ).data( 'sw', false ).removeClass( 'green' );
      }
      t_p.siblings( '.choice' ).find( 'span' ).replaceWith( this.outerHTML );
      t_p.siblings( '.choice' ).find( 'span' ).addClass( 'green' );
      t_p.fadeOut();
      var se = time( v * 1 );
      params.data.st = se.st;
      params.data.et = se.et;
    } else {
      params.data[ lx ] = v;
      t.addClass( 'green' ).siblings().removeClass( 'green' );
    }
    params.data.p = '1';
    public_vars.$page = true;

    myAjax( params );
  };

  /**
   * ========== * 搜索* ==========
   */
  public_vars.$srhbtn.click( search );

  searchMaterial.onSearch = function( searchVal ) {
    var val = searchVal;
    if ( val ) {
      bu.replaceUrl( 'keyword', val );
      behavior.addRecord( {
        category: behavior.searchTpc,
        action: val
      } );
    } else {
      return window.location.href = '/_topic';
    }
    params.data.p = '1';
    params.data.keyword = val;
    public_vars.$page = true;

    public_vars.$srhinpt.blur();
    myAjax( params );

  }

  function search( e ) {
    //e.stopImmediatePropagation();
  };

  /**
   * ===================================
   * ========== * 话题搜索页* ==========
   * ===================================
   */

  function sach_list( json ) {
    var htm = '',
      data = json.data;
    if ( data.topics ) {
      for ( i in data.topics ) {
        var t = data.topics[ i ];

        var participle = data.words || '';
        var _summary = t.summary || '';
        var _title = t.title.toString().replace( /(#)/g, "" );

        if ( !!participle.length ) {
          for ( var j in participle ) {
            _title = _title.replace( new RegExp( participle[ j ], "g" ), '<span class="green">' + participle[ j ] + '</span>' );
            _summary = _summary.replace( new RegExp( participle[ j ], "g" ), '<span class="green">' + participle[ j ] + '</span>' );
          }
        } else {
          var v_text = public_vars.$srhinpt.val();
          _title = _title.replace( new RegExp( v_text, "g" ), '<span class="green">' + v_text + '</span>' );
          _summary = _summary.replace( new RegExp( v_text, "g" ), '<span class="green">' + v_text + '</span>' );
        }

        htm += '<div class="topic_l_list_details" data-source="' + t.source + '" data-cd="' + t.cd + '" data-title="' + t.title + '"><p class="details_title">' + _title + '</p><p class="pl_icon"><span class="iconfont ' + srce.icon[ t.source ] + '"></span>' + srce.text[ t.source ] + '</p>';
        if ( bu.contains( data.comb_cds, t.cd ) ) {
          htm += '<a href="javascript:void(0)" class="details_btn iconfont icon-icon- green"></a>';
        } else {
          htm += '<a href="javascript:void(0)" class="details_btn iconfont icon-icon-"></a>';
        }

        htm += '<a href="/search/articles?search_key=' + t.title.toString().replace( /(#)/g, "" ) + '" class="details_link" data-title="' + t.title.toString().replace( /(#)/g, "" ) + '" target="_blank">相关文章</a><p class="details_summary">' + _summary + '</p></div>';
      }
    } else {
      htm = '<p class="no_content"><span class="glyphicon glyphicon-flash"></span>暂无内容</p>';
    }
    $( '.ts_num > span' ).text( data.total_rows || 0 );
    public_vars.$list.empty().append( htm );
  };

  public_vars.$paging = public_vars.$main.find( '.paging' );

  function paging( number ) {
    if ( number > 1 ) {
      public_vars.$paging.show();
    } else {
      public_vars.$paging.hide();
    }

    var cur_page = params.data[ 'p' ] - 1;
    public_vars.$paging.pagination( number * 15, {
      num_edge_entries: 2,
      num_display_entries: 4,
      items_per_page: 15,
      current_page: cur_page,
      prev_text: '上一页',
      next_text: '下一页',
      callback: function( _index, jq ) {
        if ( public_vars.$page ) {
          public_vars.$page = false;
          return;
        } else {
          params.data[ 'p' ] = _index + 1;
          myAjax( params );
        }
      }
    } );
  };

  /**
   * ========== * 点击详情* ==========
   */
  public_vars.$list.on( 'click', '.topic_l_list_details', function() {

    behavior.addRecord( {
      category: srce.text[ $( this ).data( 'source' ) ] + '话题',
      action: behavior.action.tpcRead
    } );

    if ( bu.contains( location.href, 'search' ) ) {
      window.open( 'details?cd=' + $( this ).data( 'cd' ) );
    } else {
      window.open( '_topic/details/cd/' + $( this ).data( 'cd' ) );
    }
  } ).on( 'click', '.topic_l_list_details .details_title', function( e ) {
    e.preventDefault();
  } );

  public_vars.$list.on( 'click', '.details_btn,.details_link,.pl_icon', function( e ) {
    e.stopPropagation();
  } );

  function time( j ) {
    var now = new Date(),
      t = now.format( 'yyyy-MM-dd 00:00:00' ),
      hour = 60 * 60 * 1000,
      day = hour * 24;

    var stValue = '';
    var etValue = '';

    switch ( j ) {
      case 0:
        stValue = Date.parse( t ) - ( day * 6 );
        etValue = now.getTime();
        break;
      case 1:
        stValue = now - hour;
        etValue = now.getTime();
        break;
      case 2:
        stValue = Date.parse( t );
        etValue = now.getTime();
        break;
      case 3:
        stValue = Date.parse( t ) - ( day );
        etValue = now.getTime();
        break;
      case 4:
        stValue = Date.parse( t ) - ( day * 6 );
        etValue = Date.parse( t ) - ( day );
        break;
    }
    return {
      st: stValue,
      et: etValue,
    }
  };
  //$( '.search_area .search_item' ).eq( 0 ).addClass( 'selected' );

  searchMaterial.addClassByIndex( 0 );
  window.onunload = function( e ) {
    window.scrollTo( 0, 0 );
  };

  login.addLoginCallback( function() {
    myAjax( aside );
    myAjax( params );
  } );

  /**
   *=================
   * 对比列表
   *=================
   */
  var aside_wrap = $( '.content_wrapper' );
  var aside = {
    u: '/_topic/get_comb_compare',
    callBack: parallel_list
  };

  var srce = {
    text: {
      'd.weibo.com': '新浪微博',
      'top.baidu.com': '百度风云榜',
      'top.sogou.com': '搜狗热搜榜',
      'top.so.com': '360热搜榜',
    },
    icon: {
      'd.weibo.com': 'icon-iconfontweibo',
      'top.baidu.com': 'icon-baidu',
      'top.sogou.com': 'icon-sougou red',
      'top.so.com': 'icon-icon-test',
    }
  };
  myAjax( aside );

  function parallel_list( data ) {
    var data = typeof data === 'string' ? $.parseJSON( data ) : data;
    var htm = '';
    public_vars.i = ( data.data.total == 0 ) ? '' : ( data.data.total * 1 );
    if ( data.data.total == 0 ) {
      htm = '<p><span class="glyphicon glyphicon-flash"></span>&nbsp;暂无内容</p>';
    } else {
      htm += '<div class="delete_btn"><span class="remove_all" data-num="all">全部移出</span></div>'
      for ( i in data.data.topic_comb ) {
        var $data = data.data.topic_comb[ i ];
        htm += '<div class="contrast_info" data-cd="' + $data.cd + '"><p>' + $data.title.toString().replace( /(#)/g, "" ) + '</p><button type="button" class="icon_mark"><span class="iconfont ' + srce.icon[ $data.source ] + '"></span>' + srce.text[ $data.source ] + '</button> <button type="button" class="remove_btn pull-right">移出对比</button> </div>';
      }
    }
    aside_wrap.find( '.contrast_list' ).empty().append( htm );
    $( '.contrast_number' ).text( public_vars.i );
  };
  /**
   * ========== * 加入对比* ==========
   */
  public_vars.$list.on( 'click', '.details_btn', function( e ) {
    e.stopPropagation();
    if ( $( this ).hasClass( 'green' ) ) {
      ShowTitleMessage.showWarning( '已加入对比列表！', showTime );
      return;
    }
    behavior.addRecord( {
      category: behavior.topicComparison,
      action: behavior.action.click
    } );
    var offset = $( this ).offset();
    var endOffset = $( ".merger" ).offset();
    $( "<span class='iconfont icon-icon- green add_contrast'></span>" ).css( {
      top: offset.top,
      left: offset.left
    } ).appendTo( 'body' ).animate( {
      top: endOffset.top + 4,
      left: endOffset.left,
      fontSize: 20
    }, 800, function() {
      $( '.add_contrast' ).remove();
    } );
    var $this = $( this );
    var $data;
    $data = {
      cd: $this.parent().data( 'cd' ),
      title: $this.parent().data( 'title' ),
      source: $this.parent().data( 'source' )
    }
    $.ajax( {
      type: 'post',
      url: '/_topic/add_topic',
      data: {
        cd: $data.cd,
        title: $data.title,
        source: $data.source,
      },
      success: function( data ) {
        var json = typeof data === 'string' ? $.parseJSON( data ) : data;
        if ( json.ret == 0 ) {
          $this.addClass( 'green' );
          parallel_list( json );
        } else {
          ShowTitleMessage.showWarning( json.msg, showTime );
        }
      }
    } );
  } );

  aside_wrap.find( '.contrast_btn' ).click( parallel_btn );
  aside_wrap.on( 'click', '.remove_btn', aside_remove );
  aside_wrap.on( 'click', '.remove_all', aside_remove );

  function parallel_btn() {
    if ( public_vars.i < 2 || public_vars.i == undefined ) {
      ShowTitleMessage.showWarning( '请选择对比的话题,最少选择两个', showTime );
      return false;
    } else {
      window.open( 'contrast', 'contrast' );
    }
  };

  function aside_remove() {
    var t = $( this );
    var _cd = '';
    if ( t.data( 'num' ) == 'all' ) {
      aside_wrap.find( '.contrast_info' ).each( function() {
        if ( _cd.length > 1 ) {
          _cd += ',';
        }
        _cd += $( this ).data( 'cd' );
      } )
    } else {
      _cd = t.parent().data( 'cd' );
    }
    $.ajax( {
      type: 'post',
      url: '/_topic/del_topic',
      data: {
        cd: _cd
      },
      success: function( data ) {
        var d = typeof data === 'string' ? $.parseJSON( data ) : data;
        if ( d.ret == 0 ) {
          if ( t.data( 'num' ) == 'all' ) {
            aside_wrap.find( '.contrast_list' ).children().remove();
            public_vars.$list.find( '.details_btn' ).removeClass( 'green' );
            public_vars.i = 0;
          } else {
            t.parent().remove();
            public_vars.$list.find( '[data-cd=' + _cd + ']' ).find( '.details_btn' ).removeClass( 'green' );
            public_vars.i -= 1;
          }
          var j = ( public_vars.i == 0 ) ? '' : public_vars.i;
          $( '.contrast_number' ).text( j );
          if ( public_vars.i == 0 ) {
            aside_wrap.find( '.contrast_list' ).empty().append( '<p><span class="glyphicon glyphicon-flash"></span>&nbsp;暂无内容</p>' );
          }
        }
      }
    } )
  };
} );